package com.albon.main;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.albon.alarm.BaseballSetAlarm;
import com.albon.baseball.Baseball;
import com.albon.baseball.BaseballAdapter;
import com.albon.baseball.BaseballLeague;

import com.albon.baseball.DatabaseHelper;

import com.albon.sportsalarm.R;
import com.albon.util.JsonNetwork;
import com.albon.util.Logg;
import com.albon.util.NetworkComplete;
import com.albon.util.Schedule_Calendar;
import com.albon.util.UrlList;

@SuppressLint("ValidFragment")
public class BaseballFragment extends Fragment implements OnClickListener {
	private final String TAG = "BaseballFragment";
		
	private String league_title = "";
    private String league_name = "";
    private int world = 0;
    private DatabaseHelper mDBHelper = null;
    private SQLiteDatabase db = null;
    
    private String mYear; //올해
    private String mMonth; //이번달 
    private String mDay; //오늘
    
    private Schedule_Calendar sc;
    private ImageView btn_menu;
    private ImageView btn_month;
    private ImageView leage;
    private ListView listView;
	private TextView titleText;
	private TextView monthText;
	private TextView dayText;
	private Button dayPrevious;
    private Button dayNext;
    private Context mContext;
    
    private BaseballAdapter mBaseballAdapter;
    static int TODAY = UrlList.TODAY;
	
	
	public BaseballFragment(String league_title, String league_name, int world) {
		//mColorRes = colorRes;
		this.league_title = league_title;
		this.league_name = league_name;
		this.world = world;
		setRetainInstance(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		 mDBHelper = new DatabaseHelper(getActivity(), DatabaseHelper.DATABASE_NAME);
	        if(db == null){        	
	        	db = mDBHelper.getWritableDatabase(); 
			}
	    mContext = getActivity();
	   
	    sc = new Schedule_Calendar();
		//baseball_packet();
		return inflater.inflate(R.layout.baseball_league_day, container ,false);
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	
		init();	
		
		setDayText();
		
	}
	
	private void init(){
    	titleText = (TextView)getView().findViewById(R.id.title);
    	titleText.setText(league_title);
    	monthText = (TextView)getView().findViewById(R.id.monthText);
    	dayText = (TextView)getView().findViewById(R.id.dayText);
    	dayPrevious = (Button)getView().findViewById(R.id.dayPrevious);
    	dayPrevious.setOnClickListener(this);
    	dayNext = (Button)getView().findViewById(R.id.dayNext);
    	dayNext.setOnClickListener(this);    	
        
    	//data = new ArrayList<HashMap<String, String>>();
			
		listView = (ListView)getView().findViewById(R.id.listView1);
		
		btn_menu = (ImageView)getView().findViewById(R.id.btn_menu);
		btn_menu.setOnClickListener(this);    	
		btn_month = (ImageView)getView().findViewById(R.id.btn_month);
		btn_month.setOnClickListener(this);    	
		leage = (ImageView)getView().findViewById(R.id.leage);
		
		if(world==0){
			leage.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("ic_list_mlb","drawable","com.albon.sportsalarm")));
//			time_colon1.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("time_colon1","drawable",getPackageName())));
		}else{
			leage.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("ic_list_kbo","drawable","com.albon.sportsalarm")));
		}
		
    }
	
	private void setDayText() {
        mYear = sc.getCurYear();
        mMonth = sc.getCurMonth();
        mDay = sc.getCurDay();
		 //Logg.d(TAG, "mYear : "+mYear);
		 //Logg.d(TAG, "mMonth : "+mMonth);
		 //Logg.d(TAG, "mDay : "+mDay);
		 monthText.setText(mMonth);
		 dayText.setText(mDay);
		 baseball_packet();	
    }
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		//outState.putInt("mColorRes", mColorRes);
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_menu:
			AlbonMain fca = (AlbonMain) getActivity();
			fca.getSlidingMenu().showMenu();
			break;
		case R.id.btn_month:
			if(world==0){
				Intent mlb_group_intent = new Intent(getActivity(), BaseballLeague.class);
			 	mlb_group_intent.putExtra("league_name", "mlb");
			 	mlb_group_intent.putExtra("league_title",  getText(R.string.mlb).toString());
			 	mlb_group_intent.putExtra("world",  0);
			    startActivity(mlb_group_intent);
			}else{
			    Intent kbo_group_intent = new Intent(getActivity(), BaseballLeague.class);
				kbo_group_intent.putExtra("league_name", "kbo");
				kbo_group_intent.putExtra("league_title",  getText(R.string.kbo).toString());
				kbo_group_intent.putExtra("world",  1);
				startActivity(kbo_group_intent);
				
			}
			break;
		case R.id.dayPrevious:			
			sc.setPreviousDay();
			--TODAY ;
			setDayText();
			break;
			
		case R.id.dayNext:
			
			sc.setNextDay();
			++TODAY ;
			setDayText();
			break;
		default:
			break;
		}
		
	}
	boolean isProgress = true;
	ArrayList<Baseball> baseball = new ArrayList<Baseball>();
	public void baseball_packet(){
		Logg.e(TAG, "baseball_packet");
		ArrayList<String>nameList = new ArrayList<String>();
		ArrayList<String>postList = new ArrayList<String>();
		String urlString, dataType;
		nameList.clear();
		postList.clear();
		urlString = UrlList.IP+UrlList.BASEBALL+UrlList.DAY+"/"+TODAY+"/"+league_name;
		dataType = UrlList.GET;
		JsonNetwork mNet = new JsonNetwork(getActivity(), nameList, postList, urlString, dataType);
		mNet.setNetWorkComplete(new NetworkComplete() {
			
			@Override
			public void onNetWorkComplete(boolean isSuccess, String jsonData) {
				// TODO Auto-generated method stub
				if(isSuccess)
				{
					try {
						JSONArray array = new JSONArray(jsonData);
						int size = array.length();
						baseball.clear();
						for(int i=0;i<size;i++)
						{
							JSONObject order = (JSONObject)array.get(i);
							Baseball mData = new Baseball(mContext, order.toString(), mYear, mMonth, mDay);
							//adapter에서 사용할 데이터 setBtnClicked,setmYear,setmMonth
							mData.setBtnClicked(Boolean.valueOf(mData.getEnable()));
							mData.setmYear(mYear);
							mData.setmMonth(mMonth);
							baseball.add(mData);
						}
						Logg.d(TAG, "baseball : "+baseball.size());
						listViewUpdate();
					} catch (Exception e) {
						// TODO: handle exception
						Logg.e(TAG, "e : "+e);
					}
				}else{
					
					if(jsonData!=null)
					{
						
					}
					else
					{
						Toast.makeText(getActivity(), UrlList.Error, 1000).show();
					}
				}
			}
		});
		mNet.setProgress(isProgress);
		mNet.onConnect();
	}
	
	private void listViewUpdate() {
			
		mBaseballAdapter = new BaseballAdapter(getActivity(), R.layout.sports_row_item, baseball);
		mBaseballAdapter.notifyDataSetChanged();
		listView.setAdapter(mBaseballAdapter);
			//listView.setOnTouchListener(mOnTouchListener);
		listView.setOnItemClickListener(alarmOnItemClickListener);
		}
	
//클릭이벤트
	AdapterView.OnItemClickListener alarmOnItemClickListener = new AdapterView.OnItemClickListener(){

		public void onItemClick(AdapterView parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			Baseball baseball = (Baseball) view.getTag();
			Log.d(TAG, "onClick id : "+id+", view id = "+baseball.getId());
			Log.d(TAG, "onClick id : "+id+", baseball.getScore() = "+baseball.getScore());
			Log.d(TAG, "mYear : "+ mYear);
			Log.d(TAG, "mMonth : "+mMonth);
			
			if(baseball.getScore().equals(":")){ // 스코어가 없는것만 알람 설정할수 있도록
				Intent set_alarm_intent = new Intent(getActivity(), BaseballSetAlarm.class);
				set_alarm_intent.putExtra("league_title", league_title);
				set_alarm_intent.putExtra("compare_date", baseball.getCompare_date());
				set_alarm_intent.putExtra("a_team", baseball.getA_team());
				set_alarm_intent.putExtra("b_team", baseball.getB_team());
				set_alarm_intent.putExtra("real_date", baseball.getReal_date());
				set_alarm_intent.putExtra("real_time", baseball.getReal_time());
				set_alarm_intent.putExtra("year", mYear);
				set_alarm_intent.putExtra("month", mMonth);
				set_alarm_intent.putExtra("stadium", baseball.getStadium());
				
				startActivity(set_alarm_intent);
			}else{
				Toast.makeText(getActivity(), R.string.past_game, Toast.LENGTH_SHORT).show();
			}
		}
		
	};
}
